﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.InteropServices;
using VsxFactory.Modeling.VisualStudio;
using VsxFactory.Modeling.Strategies;

namespace VsxFactory.Modeling.StrategyManager.Strategies
{
    [GuidAttribute(DependencyFileStrategyT4ExtenderProvider.Guid)]
    class DependencyFileStrategyT4ExtenderProvider : StrategyExtenderProvider 
    {
        public const string Guid = "DB01086F-02BE-47E0-BC8C-74EA68CDADCE";
        private DependentFileStrategyProvider dependentFileStrategyProvider;

        public DependencyFileStrategyT4ExtenderProvider(DependentFileStrategyProvider dependentFileStrategyProvider) : base(dependentFileStrategyProvider.ServiceProvider)
        {
            System.Diagnostics.Contracts.Contract.Requires(dependentFileStrategyProvider != null);

            this.dependentFileStrategyProvider = dependentFileStrategyProvider;
        }

        public override string Name
        {
            get { return "DependencyFileStrategyT4Extender"; }
        }

        protected override bool CanExtendFile(string fullPath)
        {
            System.Diagnostics.Contracts.Contract.Requires(fullPath != null);
            
            // Sur les fichiers .tt et si il existe une stratégie
            bool flag =  Path.GetExtension(fullPath).Equals(".tt", StringComparison.OrdinalIgnoreCase);
            if (flag)
            {
                // Recherche si une stratégie a été définie sur au moins un modéle
                IStrategyManager sm = ServiceProvider.GetService(typeof(SStrategyManager)) as IStrategyManager;
                return sm.SolutionExplorer.CurrentSolution.AllElements.OfType<IVsProjectFileItem>().FirstOrDefault(n =>
                    {
                        DependencyFileStrategyModelExtender ext = new DependencyFileStrategyModelExtender(ServiceProvider, n, null);
                        return !String.IsNullOrWhiteSpace(ext.StrategyName);
                    }) != null;
            }
            return flag;
        }

        protected override IStrategyExtender CreateExtender(IVsProjectFileItem node)
        {
            System.Diagnostics.Contracts.Contract.Requires(node != null);

            return new DependenceFileStrategyT4Extender(ServiceProvider, node);
        }

    }
}
